package com.android.assignment.taskreminder;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class TaskReminderEditFragment extends Fragment implements
		OnTimeSetListener, OnDateSetListener, LoaderCallbacks<Cursor> {

	public static final String DEFAULT_EDIT_FRAGMENT_TAG = "editFragmentTag";

	private static final String DATE_FORMAT = "yyyy-MM-dd";
	private static final String TIME_FORMAT = "kk:mm";

	static final String YEAR = "year";
	static final String MONTH = "month";
	static final String DAY = "day";
	static final String HOUR = "hour";
	static final String MINS = "mins";
	static final String CALENDAR = "calendar";

	private EditText myTaskTitle;
	private EditText myTaskNote;
	private Button myDateButton;
	private Button myTimeButton;
	private Spinner myLoopSpinner;
	private Button myConfirmButton;
	private Calendar myCalendar;
	private long myRowID;
	ArrayAdapter<CharSequence> adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		if (savedInstanceState != null
				&& savedInstanceState.containsKey(CALENDAR)) {
			myCalendar = (Calendar) savedInstanceState
					.getSerializable(CALENDAR);
		} else {
			myCalendar = Calendar.getInstance();
		}
		Bundle arguments = getArguments();

		if (arguments != null) {
			myRowID = arguments.getLong(TaskReminderProvider.COLUMN_ROWID);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.reminder_edit, container, false);
		myTaskTitle = (EditText) v.findViewById(R.id.TaskTitle);
		myTaskNote = (EditText) v.findViewById(R.id.TaskNote);
		myDateButton = (Button) v.findViewById(R.id.remider_date);
		myTimeButton = (Button) v.findViewById(R.id.remider_time);
		myLoopSpinner = (Spinner) v.findViewById(R.id.remider_time_loop);
		myConfirmButton = (Button) v.findViewById(R.id.confirm);

		adapter = ArrayAdapter.createFromResource(
				getActivity(), R.array.loop, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		myLoopSpinner.setAdapter(adapter);
		myLoopSpinner.setOnItemSelectedListener(new OnLoopListener());
		
		myDateButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDatePicker();

			}
		});

		myTimeButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showTimePicker();

			}
		});

		myConfirmButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				ContentValues values = new ContentValues();
				values.put(TaskReminderProvider.COLUMN_ROWID, myRowID);
				values.put(TaskReminderProvider.COLUMN_TITLE, myTaskTitle
						.getText().toString());
				values.put(TaskReminderProvider.COLUMN_CONTENT, myTaskNote
						.getText().toString());
				values.put(TaskReminderProvider.COLUMN_DATE_TIME,
						myCalendar.getTimeInMillis());
				values.put(TaskReminderProvider.COLUMN_STATUS, myLoopSpinner
						.getSelectedItem().toString());
				
				if (myRowID == 0) {
					Uri itemUri = getActivity().getContentResolver().insert(
							TaskReminderProvider.CONTENT_URI, values);
					myRowID = ContentUris.parseId(itemUri);
				} else {
					int count = getActivity().getContentResolver().update(
							ContentUris.withAppendedId(
									TaskReminderProvider.CONTENT_URI, myRowID),
							values, null, null);
					if (count == -1)
						throw new IllegalStateException("Unable to update "
								+ myRowID);
				}

				Toast.makeText(getActivity(), "I will remind you at "
						+ myTimeButton.getText().toString() + ", "
						+ myDateButton.getText().toString(),
						Toast.LENGTH_SHORT).show();
				//Toast.makeText(getActivity(), values.get(TaskReminderProvider.COLUMN_STATUS) + 
				//		" spniiner " + myLoopSpinner.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
				getActivity().finish();
				new ReminderManager(getActivity()).setReminder(myRowID, myCalendar);

			}
		});

		if (myRowID != 0) {
			getLoaderManager().initLoader(0, null, this);
		} else {
			SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(getActivity());
            String defaultTitleKey = getString(R.string.pref_task_title_key);
            String defaultTimeKey = getString(R.string.pref_default_time_from_now_key);

            String defaultTitle = prefs.getString(defaultTitleKey, null);
            String defaultTime = prefs.getString(defaultTimeKey, null);

            if (defaultTitle != null)
                myTaskTitle.setText(defaultTitle);

            if (defaultTime != null && defaultTime.length()>0 )
                myCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));

            updateMyButton();

		}
		return v;

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);

		outState.putSerializable(CALENDAR, myCalendar);
	}

	private void showDatePicker() {
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		DialogFragment newFragment = new DatePickerDialogFragment();
		Bundle args = new Bundle();
		args.putInt(YEAR, myCalendar.get(Calendar.YEAR));
		args.putInt(MONTH, myCalendar.get(Calendar.MONTH));
		args.putInt(DAY, myCalendar.get(Calendar.DAY_OF_MONTH));
		newFragment.setArguments(args);
		newFragment.show(ft, "datePicker");
	}

	private void showTimePicker() {
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		DialogFragment fragment = new TimePickerDialogFragment();
		Bundle args = new Bundle();
		args.putInt(HOUR, myCalendar.get(Calendar.HOUR));
		args.putInt(MINS, myCalendar.get(Calendar.MINUTE));
		fragment.setArguments(args);
		fragment.show(ft, "timePicker");
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		return new CursorLoader(getActivity(), ContentUris.withAppendedId(
               TaskReminderProvider.CONTENT_URI, myRowID), null, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		// TODO Auto-generated method stub
        if (arg1.getCount() == 0) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    getActivity().finish();
                }
            });
            return;
        }

        myTaskTitle.setText(arg1.getString(arg1
                .getColumnIndexOrThrow(TaskReminderProvider.COLUMN_TITLE)));
        myTaskNote.setText(arg1.getString(arg1
                .getColumnIndexOrThrow(TaskReminderProvider.COLUMN_CONTENT)));
        String temp = arg1.getString(arg1.getColumnIndexOrThrow(TaskReminderProvider.COLUMN_STATUS));
        int position = adapter.getPosition(temp);
        myLoopSpinner.setSelection(position);
        // Get the date from the database
        Long dateInMillis = arg1.getLong(arg1
                .getColumnIndexOrThrow(TaskReminderProvider.COLUMN_DATE_TIME));
        Date date = new Date(dateInMillis);
        myCalendar.setTime(date);

        updateMyButton();


	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		myCalendar.set(Calendar.YEAR, year);
		myCalendar.set(Calendar.MONTH, monthOfYear);
		myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
		updateMyButton();
	}

	@Override
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		// TODO Auto-generated method stub
		myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
		myCalendar.set(Calendar.MINUTE, minute);
		updateMyButton();
	}

	private void updateMyButton() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
		String dateForButton = dateFormat.format(myCalendar.getTime());
		myDateButton.setText(dateForButton);

		SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
		String timeForButton = timeFormat.format(myCalendar.getTime());
		myTimeButton.setText(timeForButton);
	}

}
